package com.bbcare.followup.plat.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.bbcare.comm.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisConnectionException;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.department.plat.service.IBsStaticParamService;
import com.bbcare.department.plat.service.IDepartmentBasicService;
import com.bbcare.followup.plat.entity.FuAssessMentPosition;
import com.bbcare.followup.plat.entity.Patient;
import com.bbcare.followup.plat.entity.PtEvaluationResult;
import com.bbcare.followup.plat.service.IFollowEvaluationScoreService;
import com.bbcare.followup.plat.service.IFollowEvaluationService;
import com.bbcare.followup.plat.service.IMabcEvaluationService;
import com.bbcare.followup.plat.service.IPatientInfoHisService;
import com.bbcare.followup.plat.service.IPatientService;
import com.bbcare.followup.plat.store.ibatis.IFollowEvaluationDAO;
import com.bbcare.followup.plat.store.ibatis.IPatientDAO;

/**
 *
 * @name:       MABC评估服务类
 * @author:       tao
 * @createTime:   2018年3月9日
 * @description:  MabcEvaluationService.java
 * @modify:
 *
 */
@Service
public class MabcEvaluationService implements IMabcEvaluationService {
    private final Log logger = LogFactory.getLog(MabcEvaluationService.class);

    @Autowired
    private IPatientService patientService;

    @Autowired
	private IBsStaticParamService bsStaticParamService;

    @Autowired
	private IFollowEvaluationDAO followEvaluationDAO;

    @Autowired
    private IDepartmentBasicService deparmentBasicService;

    @Autowired
    private IFollowEvaluationService followEvaluationService;

    @Autowired
    private IPatientInfoHisService patientInfoHisService;

    @Autowired
    private  IFollowEvaluationScoreService followEvaluationScoreService;

    @Resource(name = "jedisPool")
	private JedisPool jedisPool;

    @Autowired
	private IPatientDAO patientDao;

	@Override
	public Map<String, Object> checkUserInfo(Map<String, Object> map)
			throws Exception {
		logger.info("in  checkUserInfo");

		Map<String,Object> patientMap= null;
//		List<Patient> patientList = patientService.getPatientList(map);
		map.put("userStatus", Constants.PATIENT_QUEUESCHEME_USER_STATUS_NOMAL);// 队列中正常状态下的用户
		List<Map<String, Object>> patientList = patientDao.selectPtSchemeByCondition(map);

		if(CollectionUtils.isEmpty(patientList)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST,"没有查询到宝宝信息，请和医生确认填写信息是否正确！");
		}

		Map<String,Object> pt = patientList.get(0);
		String birthday ="";
		if(!StringUtils.isEmpty(pt.get("birthday"))){
			birthday =pt.get("birthday").toString();
		}

	    String pregnancyDay = "";
	    if(StringUtils.isEmpty(pt.get("pregnancyDay"))){
	    	pregnancyDay = "280";
	    }else{
	    	pregnancyDay = pt.get("pregnancyDay").toString();
	    }
	    int ageMonth = 0;
	    //1: 3岁9月 -4岁3月   按每月30天 整月估算  3*12+9=45 ~4*12+3 51

	    Long birthLong=ToolUtils.getCorrect(birthday,Integer.parseInt(pregnancyDay));//生日时间戳
		ageMonth=(int)((new Date().getTime()-birthLong)/(1000*60*60*24)/Constants.MONTH_DAY);
	    //2：按自然月份时间计算
		//3岁9月(45) -4岁3月(51),4岁9月(57) -5岁3月(63),5岁9月(69) -6岁3月(75)
		if(ageMonth>=45 && ageMonth<=51){
			patientMap =  new HashMap<String,Object>();
			patientMap.put("birthday",birthday);
			patientMap.put("hisNo",pt.get("hisNo"));
			patientMap.put("userId",pt.get("id"));
			patientMap.put("userName",pt.get("userName"));
			//年龄状态 0：3岁9月-4岁3月龄
			patientMap.put("ageState","0");
		}else if(ageMonth>=57 && ageMonth<=63){
			patientMap =  new HashMap<String,Object>();
			patientMap.put("birthday",birthday);
			patientMap.put("hisNo",pt.get("hisNo"));
			patientMap.put("userId",pt.get("id"));
			patientMap.put("userName",pt.get("userName"));
			//年龄状态 1：4岁9月-5岁3月龄
			patientMap.put("ageState","1");
		}else if(ageMonth>=69 && ageMonth<=75){
			patientMap =  new HashMap<String,Object>();
			patientMap.put("birthday",birthday);
			patientMap.put("hisNo",pt.get("hisNo"));
			patientMap.put("userId",pt.get("id"));
			patientMap.put("userName",pt.get("userName"));
			//年龄状态 2：5岁9月-6岁3月龄
			patientMap.put("ageState","2");
		}else{
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_AGE_OUT_RANGE,"对不起，您的年龄不在填写范围内！");
		}

		return patientMap;
	}

	@Override
	public Map<String, Object> getMabcCompleteList(Map<String, Object> paramMap)
			throws Exception {
		logger.info("in  getCompleteList");
		String userId = (String) paramMap.get("userId");
        String tenantId = (String) paramMap.get("tenantId");
        String busiId = (String) paramMap.get("busiId");
        String ageState = (String) paramMap.get("ageState");

		List<Map<String, Object>> birthdayList = followEvaluationDAO.selectbirthdayByuserId(userId);
		Map<String,Object> pt = birthdayList.get(0);

		String birthday ="";
		if(!StringUtils.isEmpty(pt.get("birthday"))){
			birthday =pt.get("birthday").toString();
		}

		String pregnancyDay = "";
		if(StringUtils.isEmpty(pt.get("pregnancyDay"))){
			pregnancyDay = "280";
		}else{
			pregnancyDay = pt.get("pregnancyDay").toString();
		}
		int ageMonth = 0;
		//1: 3岁9月 -4岁3月   按每月30天 整月估算  3*12+9=45 ~4*12+3 51

		Long birthLong=ToolUtils.getCorrect(birthday,Integer.parseInt(pregnancyDay));//生日时间戳
		ageMonth=(int)((new Date().getTime()-birthLong)/(1000*60*60*24)/Constants.MONTH_DAY);
		//2：按自然月份时间计算
		//3岁9月(45) -4岁3月(51),4岁9月(57) -5岁3月(63),5岁9月(69) -6岁3月(75)

        String excludeBusiId = (String) paramMap.get("excludeBusiId"); //排除
		Map<String,Object> rspMap= new HashMap<String,Object>();

		Map<String,Object> queryMap = new HashMap<String,Object>();
		if (("0").equals(ageState)) {
			queryMap.put("type",Constants.ASSESSMENT_MABC_TYPE);
		} else if (("1").equals(ageState)){
			queryMap.put("type",Constants.ASSESSMENT_FIVE_MABC_TYPE);
		} else if (("2").equals(ageState)){
			queryMap.put("type",Constants.ASSESSMENT_SIX_MABC_TYPE);
		}else if (ageMonth >= 45 && ageMonth <= 51) {
			queryMap.put("type",Constants.ASSESSMENT_MABC_TYPE);
		} else if (ageMonth >= 57 && ageMonth <= 63){
			queryMap.put("type",Constants.ASSESSMENT_FIVE_MABC_TYPE);
		} else if (ageMonth >= 69 && ageMonth <= 75){
			queryMap.put("type",Constants.ASSESSMENT_SIX_MABC_TYPE);
		}
		if(!StringUtils.isEmpty(busiId)){
			queryMap.put("paramCode",busiId);
		}

		List<Map<String,Object>> busiList = bsStaticParamService.getStaticParamsByCondition(queryMap);

		List<Map<String,Object>> busiListTmp = new ArrayList<Map<String,Object>>();
		List<String> typeList = new ArrayList<String>();
		if(!CollectionUtils.isEmpty(busiList)){
			for (int i = 0; i < busiList.size(); i++) {
				String tempBusiId = (String)busiList.get(i).get("paramCode");
				if(!StringUtils.isEmpty(excludeBusiId) && excludeBusiId.equals(tempBusiId)){
					continue;
				}
				typeList.add(tempBusiId);
				busiListTmp.add(busiList.get(i));
			}
		}

		//查询每个评估的状态
		queryMap.clear();
		queryMap.put("userId",userId);
		queryMap.put("tenantId",tenantId);
		if(CollectionUtils.isEmpty(typeList)){
			return rspMap;
		}
		queryMap.put("typeList",typeList);
		List<Map<String,Object>> answerList = followEvaluationDAO.selectMabcEvaluationRecord(queryMap);
		Map<String,Map<String,Object>> answerMap = new HashMap<String,Map<String,Object>>();
		if(!CollectionUtils.isEmpty(answerList)){
			for (int i = 0; i < answerList.size(); i++) {
				String key = (String)answerList.get(i).get("busiId");
				answerList.get(i).put("createTime", answerList.get(i).get("createTime").toString());
				answerMap.put(key,answerList.get(i));
			}
		}

		List<Map<String,Object>> rspList = new ArrayList<Map<String,Object>>();
		if(!CollectionUtils.isEmpty(busiListTmp)){
			for (int i = 0; i < busiListTmp.size(); i++) {
				Map<String,Object> tempMap = new HashMap<String,Object>();
				String key = (String)busiListTmp.get(i).get("paramCode");
				String paramName = (String)busiListTmp.get(i).get("paramName");
				if(answerMap.containsKey(key)){
					tempMap.put("status","1");//完成
					tempMap.put("createTime",answerMap.get(key).get("createTime"));
					tempMap.put("answerId",answerMap.get(key).get("answerId"));
				}else{
					tempMap.put("status","0");
				}
				tempMap.put("busiId",key);
				tempMap.put("busiName",paramName);
				rspList.add(tempMap);
			}
		}

		rspMap.put("questionList",rspList);
		return rspMap;
	}

	@Override
	public Map<String, Object> getMabcAnswerDetail(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		String evaluationId =(String)map.get("evaluationId");
		Map<String, Object> rspMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = followEvaluationService.selectPtEvaluationResultDetail(map);
		if(null == resultMap){
			return null;
		}
		try {
			String evaluationType =(String)resultMap.get("type");
			map.put("busiId", evaluationType);
			List<JSONObject> postionList = this.getMabcCommonPostion(map);//获取问卷
			String result = (String)resultMap.get("answerResult");
			//传入答题 结果
			for(int m = 0 ;m<postionList.size();m++){
				String section = postionList.get(m).getString("section");
				JSONArray questionList = postionList.get(m).getJSONArray("questions");
				JSONObject jsonEsb = null;
				if(null != result && null != JSON.parseObject(result)){
					jsonEsb = JSON.parseObject(result).getJSONObject(section);
				}
				if(null != questionList && null != jsonEsb){
					for(int i = 0 ;i<questionList.size();i++){
						String id = questionList.getJSONObject(i).getString("id");
						String type = questionList.getJSONObject(i).getString("type");
						JSONArray answers = questionList.getJSONObject(i).getJSONArray("answer");
						JSONArray list = questionList.getJSONObject(i).getJSONArray("list");

						if(null != answers){
							for(int j = 0 ;j<answers.size();j++){
								JSONObject obj = answers.getJSONObject(j);
								String idStr = obj.getString("id");
								String name =  obj.getString("name");
								answers.getJSONObject(j).put("name",idStr+".  "+name);
							}
						}

						if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_RADIO.equals(type) || StringUtils.isEmpty(type)
								){
							String answerId = jsonEsb.getString(id);
							if(null != answers && !StringUtils.isEmpty(answerId)){
								for(int j = 0 ;j<answers.size();j++){
									JSONObject obj = answers.getJSONObject(j);
									String idStr = obj.getString("id");
									//SDQ答案获取 APP特殊处理
									if(answerId.equals(idStr)){
										obj.put("checked",true);
									}
								}
							}
						}else if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_timeText.equals(type)||
								Constants.EVALUATION_QUESTION_ANSWER_OPTION_TEXT.equals(type)){
							String answerId = jsonEsb.getString(id);
							questionList.getJSONObject(i).put("value",answerId);
						}else if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_RadioAndText.equals(type)
								|| Constants.EVALUATION_QUESTION_ANSWER_OPTION_checkboxAndText.equals(type)){
							Object answerObj = jsonEsb.get(id); //
							JSONObject answerJson = null;
							if(null != answers && !StringUtils.isEmpty(answerObj)){
								for(int j = 0 ;j<answers.size();j++){
									JSONObject obj = answers.getJSONObject(j);
									String idStr = obj.getString("id");

									if(answerObj instanceof String){
										if(idStr.equals((String)answerObj)){
											obj.put("checked",true);
										}
									}else if(answerObj instanceof JSONObject){
										answerJson = (JSONObject)answerObj;
										if(answerJson.containsKey(idStr)){
											obj.put("checked",true);
										}
									}

									if(obj.containsKey("relations")){//如果有关联
										/*String relationType =obj.getString("relationType");
										if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_TEXT.equals(relationType)){
										}*/
										JSONArray relations = obj.getJSONArray("relations");
										if(null != relations && null!= answerJson &&
												null != answerJson.getJSONObject(idStr)){
											JSONObject relationAnswer = answerJson.getJSONObject(idStr);
											for(int k = 0;k<relations.size();k++){
												String ralationId = relations.getJSONObject(k).getString("id");
												if(relationAnswer.containsKey(ralationId)){
													relations.getJSONObject(k).put("value",relationAnswer.getString(ralationId));
												}
											}
										}
									}
								}
							}
						}else if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_RadioAndRadio.equals(type)
								|| Constants.EVALUATION_QUESTION_ANSWER_OPTION_checkboxAndRadio.equals(type)
								|| Constants.EVALUATION_QUESTION_ANSWER_OPTION_CHECKBOX.equals(type)){
							Object answerObj = jsonEsb.get(id); //
							JSONObject answerJson = null;

							if(null != answers && !StringUtils.isEmpty(answerObj)){
								for(int j = 0 ;j<answers.size();j++){
									JSONObject obj = answers.getJSONObject(j);
									String idStr = obj.getString("id");
									if(answerObj instanceof String){
										if(idStr.equals((String)answerObj)){
											obj.put("checked",true);
										}
									}else if(answerObj instanceof JSONObject){
										answerJson = (JSONObject)answerObj;
										if(answerJson.containsKey(idStr)){
											obj.put("checked",true);
										}
									}

									if(obj.containsKey("relations")){//如果有关联
										/*String relationType =obj.getString("relationType");
										if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_TEXT.equals(relationType)){
										}*/
										JSONArray relations = obj.getJSONArray("relations");
										if(null != relations && null!= answerJson
												&& null != answerJson.get(idStr)){
											for(int k = 0;k<relations.size();k++){
												String ralationId = relations.getJSONObject(k).getString("id");
												if(ralationId.equals(answerJson.get(idStr))){
													relations.getJSONObject(k).put("checked",true);
												}
											}
										}
									}
								}
							}
						}else if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_listAndText.equals(type)){
							Object answerObj = jsonEsb.get(id); //
							JSONObject answerJson = null;
							if(answerObj instanceof JSONObject){
								answerJson = (JSONObject)answerObj;
							}

							if(null != list && !StringUtils.isEmpty(answerJson)){
								for(int j = 0 ;j<list.size();j++){
									JSONObject obj = list.getJSONObject(j);
									String idStr = obj.getString("id");
									if(answerJson.containsKey(idStr)){
										obj.put("value",answerJson.get(idStr));
									}
								}
							}
						}else if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_mutilListRadio.equals(type)){
							Object answerObj = jsonEsb.get(id); //
							JSONObject answerJson = null;
							if(answerObj instanceof JSONObject){
								answerJson = (JSONObject)answerObj;
							}

							if(null != list && !StringUtils.isEmpty(answerJson)){
								for(int j = 0 ;j<list.size();j++){
									JSONObject obj = list.getJSONObject(j);
									String idStr = obj.getString("id");

									if(obj.containsKey("childList")){//如果有关联
										/*String relationType =obj.getString("relationType");
										if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_TEXT.equals(relationType)){
										}* child:{"1":{"1":"1","2":"2"}}*/
										JSONArray childList = obj.getJSONArray("childList");
										if(null != childList && null != answerJson.get(idStr)){
											JSONObject childAnswer = answerJson.getJSONObject(idStr);
											for(int k = 0;k<childList.size();k++){
												String childId = childList.getJSONObject(k).getString("id");
//												String childName =  childList.getJSONObject(k).getString("name");

												JSONArray childAnswers = childList.getJSONObject(k).getJSONArray("answer");
												if(null != childAnswers){
													for(int n = 0;n<childAnswers.size();n++){
														String childAnswerId = childAnswers.getJSONObject(n).getString("id");
														if(childAnswerId.equals(childAnswer.get(childId))){
															childAnswers.getJSONObject(n).put("checked",true);
														}
													}
												}

//												childList.getJSONObject(k).put("name",childId+"."+childName);
											}
										}
									}
								}
							}
						}else if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_mutilListText.equals(type)){
							Object answerObj = jsonEsb.get(id); //
							JSONObject answerJson = null;
							if(answerObj instanceof JSONObject){
								answerJson = (JSONObject)answerObj;
							}

							if(null != list && !StringUtils.isEmpty(answerJson)){
								for(int j = 0 ;j<list.size();j++){
									JSONObject obj = list.getJSONObject(j);
									String idStr = obj.getString("id");

									if(obj.containsKey("childList")){//如果有关联
										/*String relationType =obj.getString("relationType");
										if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_TEXT.equals(relationType)){
										}*/
										JSONArray childList = obj.getJSONArray("childList");
										if(null != childList && null != answerJson.get(idStr)){
											JSONObject childAnswer = answerJson.getJSONObject(idStr);
											for(int k = 0;k<childList.size();k++){
												String childId = childList.getJSONObject(k).getString("id");
												if(childAnswer.containsKey(childId)){
													childList.getJSONObject(k).put("value",childAnswer.getString(childId));
												}
											}
										}
									}
								}
							}
						}else if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_listText.equals(type)){
							Object answerObj = jsonEsb.get(id); //
							JSONArray answerJson = null;
							if(answerObj instanceof JSONArray){
								answerJson = (JSONArray)answerObj;
							}
							if(null != list && !StringUtils.isEmpty(answerJson)){
								for(int j = 0 ;j<list.size();j++){
									JSONObject obj = list.getJSONObject(j);
									String idStr = obj.getString("id");
									for(int k =0;k<answerJson.size();k++){
										JSONObject answer = answerJson.getJSONObject(k);
										if(answer.containsKey(idStr)){
											obj.put("value",answer.get(idStr));
											break;
										}
									}

								}
							}
						}else if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_unFixmultilText.equals(type)){
							Object answerObj = jsonEsb.get(id); //
							JSONArray answerJson = null;
							if(answerObj instanceof JSONArray){
								answerJson = (JSONArray)answerObj;
							}

							if(null != answerJson){
								JSONArray jsonArr  = new JSONArray();
								for(int k = 0;k<answerJson.size();k++){
									JSONArray jsonArrTemp  = new JSONArray();
									JSONObject jsonTemp = answerJson.getJSONObject(k);
									for(int l= 0;l<list.size();l++){
										JSONObject jsonTempQuest = list.getJSONObject(l);
										String subId = jsonTempQuest.getString("id");
										String value = jsonTemp.getString(subId);

										JSONObject jsonNew = new JSONObject();
										jsonNew.put("value", value);
										jsonNew.putAll(jsonTempQuest);
										jsonArrTemp.add(jsonNew);

									}
									jsonArr.add(jsonArrTemp);
								}
								questionList.getJSONObject(i).put("list", jsonArr);
							}

						}
					}
				}
			}
			rspMap.put("answerResult",postionList);
			if(null != resultMap.get("result")){
				rspMap.put("score",resultMap.get("result"));
			}
			if(null != resultMap.get("createTime")){
				rspMap.put("createTime",resultMap.get("createTime"));
			}
			if(null != resultMap.get("answerId")){
				rspMap.put("answerId",resultMap.get("answerId"));
			}

			//查询指导意见
			Map<String,Object> paramMap = new HashMap<String,Object>();
			paramMap.put("evaluationId", evaluationId);
			List<Map<String,Object>> guiList =followEvaluationDAO.selectEvaluationGuides(paramMap);
			if(!CollectionUtils.isEmpty(guiList)){
				Map<String,Object> guideMap = new HashMap<String,Object>();
				guideMap.put("guideContent",guiList.get(0).get("guide"));
				guideMap.put("guideId",guiList.get(0).get("id"));
				rspMap.put("guide",guideMap);
			}

			return rspMap;
		}catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		}finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public List<JSONObject> getMabcCommonPostion(Map<String, Object> map)
			throws Exception {
		logger.info("in  getMabcCommonPostion");
		Jedis jedis = null;
		String key = (String)map.get("busiId");
		List<JSONObject> postionMap = new ArrayList<JSONObject>();
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key);

			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",key);
				FuAssessMentPosition position = followEvaluationDAO.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key,json);
				}
			}

			JSONArray arr = JSON.parseArray(json);
			if(arr == null || arr.size() ==0){ //没有问题
				return postionMap;
			}

			for(int i = 0;i<arr.size();i++){
				postionMap.add(arr.getJSONObject(i));
			}
			return postionMap;

		} catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		} finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public Map<String,Object> mabcCommonSubmit(Map<String, Object> map)
			throws Exception {
		logger.info("in  mabcCommonSubmit");
		Map<String,Object> rspMap = new HashMap<String,Object>();

		String busiId = (String)map.get("busiId");
		String userId = (String)map.get("userId");
		String tenantId = (String)map.get("tenantId");
		String taskId = (String)map.get("taskId");
		String sourceType = (String)map.get("sourceType");
		String postionIds = (String)map.get("postionIds");
		String queueId = (String)map.get("queueId");

		Map<String,Object> ptMap = new HashMap<String,Object>();
		ptMap.put("userId",userId);
		ptMap.put("tenantId",tenantId);
		Patient pt = patientService.getPatient(ptMap);
		if(pt == null ){
            throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_PATIENT_NOT_EXIST, "患者信息不存在");
		}

		PtEvaluationResult answer = new PtEvaluationResult();
		String testTime = DateUtil.getDate_8(new Date());
		Map<String,Object> scoreMap = null;
		if(Constants.MABC_HEART.equals(busiId)){//心里行为 计算得分
			//得到sdq的id
			//传入答题 结果
			JSONObject jsonObj = JSON.parseObject(postionIds);
			if(null != jsonObj){
				JSONObject sdqJsonEsb =jsonObj.getJSONObject(Constants.MABC_HEART);
				Map<String,Object> sdqMap = new HashMap<String,Object>();
				if(null != sdqJsonEsb){
					sdqMap.put("postionIds",sdqJsonEsb.toString());
//					sdqMap.put("version","MABC");
					scoreMap = getMabcSDQScore(sdqMap);
				}
			}
		}else if(Constants.MABC_SLEEP.equals(busiId)){
			//得到睡眠评估问卷的id
			//传入答题 结果
			JSONObject jsonObj = JSON.parseObject(postionIds);
			if(null != jsonObj){
				JSONObject sdqJsonEsb =jsonObj.getJSONObject(Constants.MABC_SLEEP_SITUATION);
				Map<String,Object> sdqMap = new HashMap<String,Object>();
				if(null != sdqJsonEsb){
					sdqMap.put("postionIds",sdqJsonEsb.toString());
					scoreMap = getMabcSleepScore(sdqMap);
				}

			}
		}else if(Constants.MABC_FIVE_HEART.equals(busiId)){
			//五岁心里评估得分
			//传入答题 结果
			JSONObject jsonObj = JSON.parseObject(postionIds);
			if(null != jsonObj){
				JSONObject sdqJsonEsb =jsonObj.getJSONObject(Constants.MABC_FIVE_HEART);
				Map<String,Object> sdqMap = new HashMap<String,Object>();
				if(null != sdqJsonEsb){
					sdqMap.put("postionIds",sdqJsonEsb.toString());
					scoreMap = getMabcSDQScore(sdqMap);
				}

			}
		}

		answer.setType(busiId);
		answer.setId(SeqUtil.getSeqNo());
		answer.setCreateTime(DateUtil.getSysDateA());
		if(null != scoreMap){
			answer.setScore(JSON.toJSONString(scoreMap));
		}
		answer.setResult(postionIds);
		if(StringUtils.isEmpty(sourceType)){
			answer.setSourcetype(Constants.SOURCE_TYPE_APP); //APP或微信录入
		}else{
			answer.setSourcetype(sourceType); //APP或微信录入
		}

		answer.setSourceid(userId);
		answer.setTenantId(tenantId);
		answer.setUserId(userId);
		answer.setTaskId(taskId);
		answer.setTestTime(testTime);
		answer.setQueueId(queueId);
		followEvaluationService.savePtEvaluationResult(answer,null);

		rspMap.put("answerId",answer.getId());

		//记录操作日志
		String opCode =Constants.OP_CODE_1213;
		String remark = "患者【" + pt.getUserName() + "】提交MABC问卷测评";
		try{
			if(null != pt){
				Map<String,Object> param = new HashMap<String,Object>();
				param.putAll(map);
				param.put("opUsertype",Constants.OPCODE_TYPE_PATIENT);
				param.put("type", Constants.PATIENT_ACTIVE_BUSI_TYPE_6);
				param.put("authorId",userId);
				param.put("userId",userId);
				param.put("queueId",queueId);
	            param.put("remark", remark);
				param.put("updateAccept",SeqUtil.getSeqNo());
				param.put("opCode",opCode);
				param.put("busiId",answer.getId());
				param.put("tenantId", tenantId);
				patientInfoHisService.saveOperationRecord(param);
			}
		}catch(Exception e){
			logger.error("保存上传评估操作记录表报错", e);
		}
		return rspMap;
	}


	private Map<String,Object> getMabcSleepScore(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		String postions = (String)map.get("postionIds");
		String key =Constants.MABC_SLEEP;
		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key);
			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",key);
				FuAssessMentPosition position = followEvaluationDAO.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key,json);
				}
			}

//			List<JSONObject> postionList = new ArrayList<JSONObject>();
			JSONArray questionArr = null;
			JSONArray arr = JSON.parseArray(json);
			for(int i = 0;i<arr.size();i++){
				if(null!=arr.getJSONObject(i) && Constants.MABC_SLEEP_SITUATION.equals(arr.getJSONObject(i).getString("section"))){
					questionArr = arr.getJSONObject(i).getJSONArray("questions");
				}
			}

			//传入答题 结果
			JSONObject jsonEsb = JSON.parseObject(postions);
			String normal ="正常",abnormal="风险偏高";
			int a = 0,b=0,c=0,d=0,e=0,f=0,g=0,h=0,total=0;
			//评分标准：情绪症状 ：0-3	4	5-10  ，品行问题0-2	3	4-10 ，多动0-5	6	7-10，同伴交往0-2	3	4-10，亲社会行为 10-6	5	0-4，困难总分 0-13	14-16	17-40
			Map<String,Object> aMap = new HashMap<String,Object>(),bMap = new HashMap<String,Object>(),
					cMap = new HashMap<String,Object>(),dMap = new HashMap<String,Object>(),
					eMap = new HashMap<String,Object>(),fMap = new HashMap<String,Object>(),
					gMap = new HashMap<String,Object>(),hMap = new HashMap<String,Object>(),
					totalMap = new HashMap<String,Object>();

			//后续修改跟 答题结果循环
			for(int i = 0 ;i<questionArr.size();i++){
				String factor = questionArr.getJSONObject(i).getString("factor");
				String id = questionArr.getJSONObject(i).getString("id");
//				int number = Integer.parseInt(id);
//				if(number <= 31){
					String answerId = jsonEsb.getString(id);
					JSONArray answers =  questionArr.getJSONObject(i).getJSONArray("answer");
					if(null != answers && !StringUtils.isEmpty(answerId)){
						for(int j = 0 ;j<answers.size();j++){
							JSONObject obj = answers.getJSONObject(j);
							String idStr = String.valueOf(obj.getIntValue("id"));
							if(answerId.equals(idStr)){
								int score = obj.getIntValue("score");
								//总分按题目算
								total+=score;

								if(!StringUtils.isEmpty(factor)){
									String factorArr[] = factor.split(",");
									for(int k = 0;k<factorArr.length;k++){
										if(Constants.MABC_FACTOR_TYPE_A.equals(factorArr[k])){
											a+=score;
										}else if(Constants.MABC_FACTOR_TYPE_B.equals(factorArr[k])){
											b+=score;
										}else if(Constants.MABC_FACTOR_TYPE_C.equals(factorArr[k])){
											c+=score;
										}else if(Constants.MABC_FACTOR_TYPE_D.equals(factorArr[k])){
											d+=score;
										}else if(Constants.MABC_FACTOR_TYPE_E.equals(factorArr[k])){
											e+=score;
										}else if(Constants.MABC_FACTOR_TYPE_F.equals(factorArr[k])){
											f+=score;
										}else if(Constants.MABC_FACTOR_TYPE_G.equals(factorArr[k])){
											g+=score;
										}else if(Constants.MABC_FACTOR_TYPE_H.equals(factorArr[k])){
											h+=score;
										}
									}
								}
							}
						}
					}
//				}
			}
//			total = a+b+c+d+e+f+g+h;

			aMap.put("score",a);
			aMap.put("desc","睡眠阻抗");
			if(a<=10.84){
				aMap.put("result",normal);
			}else{
				aMap.put("result",abnormal);
			}

			bMap.put("score",b);
			bMap.put("desc","入睡延迟");
			if(b<=2.31){
				bMap.put("result",normal);
			}else{
				bMap.put("result",abnormal);
			}

			cMap.put("score",c);
			cMap.put("desc","睡眠持续时间");
			if(c<=5.27){
				cMap.put("result",normal);
			}else{
				cMap.put("result",abnormal);
			}

			dMap.put("score",d);
			dMap.put("desc","睡眠焦虑");
			if(d<=7.79){
				dMap.put("result",normal);
			}else{
				dMap.put("result",abnormal);
			}

			eMap.put("score",e);
			eMap.put("desc","夜醒");
			if(e<=5.29){
				eMap.put("result",normal);
			}else{
				eMap.put("result",abnormal);
			}

			fMap.put("score",f);
			fMap.put("desc","异态睡眠");
			if(f<=10.61){
				fMap.put("result",normal);
			}else{
				fMap.put("result",abnormal);
			}
			gMap.put("score",g);
			gMap.put("desc","睡眠障碍性呼吸");
			if(g<=4.50){
				gMap.put("result",normal);
			}else{
				gMap.put("result",abnormal);
			}

			hMap.put("score",h);
			hMap.put("desc","以及日间困倦");
			if(h<=15.24){
				hMap.put("result",normal);
			}else{
				hMap.put("result",abnormal);
			}
			totalMap.put("score",total);
			totalMap.put("desc","总分");
			if(total<=54){
				totalMap.put("result",normal);
			}else{
				totalMap.put("result",abnormal);
			}

			Map<String, Object> scoreMap = new HashMap<String, Object>();
			Map<String, Object> scoreDetailMap = new HashMap<String, Object>();
			scoreDetailMap.put("total",totalMap);
			scoreDetailMap.put("A",aMap);
			scoreDetailMap.put("B",bMap);
			scoreDetailMap.put("C",cMap);
			scoreDetailMap.put("D",dMap);
			scoreDetailMap.put("E",eMap);
			scoreDetailMap.put("F",fMap);
			scoreDetailMap.put("G",gMap);
			scoreDetailMap.put("H",hMap);

			scoreMap.put("score", scoreDetailMap);
			scoreMap.put("maxScore","24");
			return scoreMap;

		}catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		}finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}

	@Override
	public Map<String, Object> getMabcBasicInfo(Map<String, Object> map)
			throws Exception {
		logger.info("in  getMabcBasicInfo");
		//获取基本问卷
		String userId = (String)map.get("userId");
		String tenantId = (String)map.get("tenantId");
		String busiId = (String)map.get("busiId");// 不同年龄问卷的基本信息类型


		JSONArray answerJson = new JSONArray();
		List<JSONObject> json = this.getMabcCommonPostion(map);
		if(null != json){ //找第五题的 题目选项
			JSONArray arr = json.get(0).getJSONArray("questions");
			if(null != arr){
				for(int i  = 0 ; i < arr.size() ;i++){
					String type = arr.getJSONObject(i).getString("type");
					if(Constants.EVALUATION_QUESTION_ANSWER_OPTION_RadioAndText.equals(type)){
						answerJson = arr.getJSONObject(i).getJSONArray("answer");
						break;
					}
				}
			}
		}
		//获取答案

		Map<String,Object> queryMap  = new  HashMap<String,Object>();
		queryMap.clear();
		queryMap.put("userId",userId);
		queryMap.put("tenantId",tenantId);

		List<String> typeList = new ArrayList<String>();
		typeList.add(busiId);
		queryMap.put("typeList",typeList);
		List<Map<String,Object>> answerList = followEvaluationDAO.selectMabcEvaluationRecord(queryMap);

		//
		Map<String,Object> rspMap = new HashMap<String,Object>();
		if(!CollectionUtils.isEmpty(answerList)){
			String result ="";
			String testTime=null;
			result =  (null == answerList.get(0).get("result"))? null:answerList.get(0).get("result").toString();
			testTime = (null == answerList.get(0).get("testTime"))? null:answerList.get(0).get("testTime").toString();
//			createTime = (null == answerList.get(0).get("createTime"))? null:answerList.get(0).get("createTime").toString();

			rspMap.put("createTime", testTime);
//			rspMap.put("createTime", DateUtil.getTimeStampSec(createTime));
			if(!StringUtils.isEmpty(result)){
				JSONObject answers =  JSONObject.parseObject(result);
				rspMap.put("class", answers.get("4")==null ? "":answers.get("4"));
				rspMap.put("hisNo", answers.get("6")==null ? "":answers.get("6"));
				rspMap.put("motherName", answers.get("1")==null ? "":answers.get("1"));
				rspMap.put("school", answers.get("3")==null ? "":answers.get("3"));
				rspMap.put("userName", answers.get("2")==null ? "":answers.get("2"));

				String createName ="";

				if(null != answers.get("5") && answers.get("5") instanceof JSONObject){
					JSONObject jsonTemp = answers.getJSONObject("5").getJSONObject("5");
					if(null != jsonTemp){
						createName = jsonTemp.getString("5_5_1");
					}
				}else{
					for(int j=0;j<answerJson.size();j++){
						if(answers.get("5").equals(answerJson.getJSONObject(j).getString("id"))){
							createName = answerJson.getJSONObject(j).getString("name");
						}
					}
				}
				rspMap.put("createName", createName);
			}
		}

		return rspMap;
	}

	private Map<String,Object> getMabcSDQScore(Map<String, Object> map)
			throws Exception {
		Jedis jedis = null;
		String postions = (String)map.get("postionIds");
		String key =Constants.MABC_HEART;

		try {
			jedis = jedisPool.getResource();
			jedis.select(Constants.REDIS_DB_INDEX_EVALUATION);
			String json = jedis.hget(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key);
			if(StringUtils.isEmpty(json)){
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("field",Constants.FOLLOW_EVALUATION_PREGNANT_KEY);
				paramMap.put("key",key);
				FuAssessMentPosition position = followEvaluationDAO.selectAssessMentPosition(paramMap);
				if(null != position){
					json = position.getValue();
					jedis.hset(Constants.FOLLOW_EVALUATION_PREGNANT_KEY,key,json);
				}
			}

			JSONArray arr = JSON.parseArray(json);
			JSONArray questionArr = null;
			for(int i = 0;i<arr.size();i++){
				questionArr = arr.getJSONObject(i).getJSONArray("questions");
			}

			//传入答题 结果
			JSONObject jsonEsb = JSON.parseObject(postions);
//			String normal ="正常",dubious="可疑",abnormal="异常";
			String normal ="发育良好",dubious="低风险",abnormal="风险偏高";
			int prosocial = 0,mbd=0,emotional=0,conduct=0,companion=0,total=0;
			//评分标准：情绪症状 ：0-3	4	5-10  ，品行问题0-2	3	4-10 ，多动0-5	6	7-10，同伴交往0-2	3	4-10，亲社会行为 10-6	5	0-4，困难总分 0-13	14-16	17-40
			Map<String,Object> prosocialMap = new HashMap<String,Object>(),mbdMap = new HashMap<String,Object>(),
					emotionalMap = new HashMap<String,Object>(),conductMap = new HashMap<String,Object>(),
					companionMap = new HashMap<String,Object>(),totalMap = new HashMap<String,Object>();

			//后续修改跟 答题结果循环
			for(int i = 0 ;i<questionArr.size();i++){
				String factor = questionArr.getJSONObject(i).getString("factor");
				String id = questionArr.getJSONObject(i).getString("id");
				int number = Integer.parseInt(id);
				if(number <= 25){ //25题 之内算分  附加题暂时不算分
					String answerId = jsonEsb.getString(id);
					JSONArray answers =  questionArr.getJSONObject(i).getJSONArray("answer");
					if(null != answers && !StringUtils.isEmpty(answerId)){
						for(int j = 0 ;j<answers.size();j++){
							JSONObject obj = answers.getJSONObject(j);
							String idStr= String.valueOf(obj.getIntValue("id"));

							if(answerId.equals(idStr)){
								int score = obj.getIntValue("score");
								if(Constants.SDQ_FACTOR_TYPE_COMPANION.equals(factor)){
									companion+=score;
									break;//单选题  匹配一项及退出答案匹配循环
								}else if(Constants.SDQ_FACTOR_TYPE_CONDUCT.equals(factor)){
									conduct+=score;
									break;
								}else if(Constants.SDQ_FACTOR_TYPE_EMOTIONAL.equals(factor)){
									emotional+=score;
									break;
								}else if(Constants.SDQ_FACTOR_TYPE_MBD.equals(factor)){
									mbd+=score;
									break;
								}else if(Constants.SDQ_FACTOR_TYPE_PROSOCIAL.equals(factor)){
									prosocial+=score;
									break;
								}
							}
						}
					}
				}
			}
			total = mbd+emotional+conduct+companion;
			prosocialMap.put("score",prosocial);
			prosocialMap.put("desc","亲社会行为");
			if(prosocial>=6){
				prosocialMap.put("result",normal);
			}else if(prosocial==5){
				prosocialMap.put("result",dubious);
			}else if(prosocial>=0 && prosocial<=4){
				prosocialMap.put("result",abnormal);
			}
			mbdMap.put("score",mbd);
			mbdMap.put("desc","多动");
			if(mbd>=0 && mbd<=5){
				mbdMap.put("result",normal);
			}else if(mbd==6){
				mbdMap.put("result",dubious);
			}else if(mbd>=7){
				mbdMap.put("result",abnormal);
			}
			emotionalMap.put("score",emotional);
			emotionalMap.put("desc","情绪症状");
			if(emotional>=0 && emotional<=3){
				emotionalMap.put("result",normal);
			}else if(emotional==4){
				emotionalMap.put("result",dubious);
			}else if(emotional>=5){
				emotionalMap.put("result",abnormal);
			}
			conductMap.put("score",conduct);
			conductMap.put("desc","品行问题");
			if(conduct>=0 && conduct<=2){
				conductMap.put("result",normal);
			}else if(conduct==3){
				conductMap.put("result",dubious);
			}else if(conduct>=4){
				conductMap.put("result",abnormal);
			}

			companionMap.put("score",companion);
			companionMap.put("desc","同伴交往");
			if(companion>=0 && companion<=2){
				companionMap.put("result",normal);
			}else if(companion==3){
				companionMap.put("result",dubious);
			}else if(companion>=4 &&companion<=10){
				companionMap.put("result",abnormal);
			}

			totalMap.put("score",total);
			totalMap.put("desc","困难总分");
			if(total>=0 && total<=13){
				totalMap.put("result",normal);
			}else if(total>=14 && total<=16){
				totalMap.put("result",dubious);
			}else if(total>=17){
				totalMap.put("result",abnormal);
			}

			Map<String, Object> scoreMap = new HashMap<String, Object>();
			Map<String, Object> scoreDetailMap = new HashMap<String, Object>();
			scoreDetailMap.put("diffTotal",totalMap);
			scoreDetailMap.put("companion",companionMap);
			scoreDetailMap.put("emotional",emotionalMap);
			scoreDetailMap.put("conduct",conductMap);
			scoreDetailMap.put("mbd",mbdMap);
			scoreDetailMap.put("prosocial",prosocialMap);
			scoreMap.put("score", scoreDetailMap);
			scoreMap.put("maxScore","10");
			return scoreMap;

		}catch (JedisConnectionException jex) {
			logger.error("redis连接异常..." + jex.getMessage());
			throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_ERROR,"Redis缓存连接失败!"));
		}finally {
			if (null != jedis) {
				try {
					jedis.close();
					logger.warn("close redis connection...");
				} catch (Exception ex) {
					ex.printStackTrace();
					throw (new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_REDIS_CONNECT_CLOSE_FAILED,"Redis缓存关闭失败!"));
				}
			}
		}
	}


	@Override
	public List<Map<String, Object>> getMabcAppList(Map<String, Object> paramMap)
			throws Exception {
		logger.info("in  getMabcAppList");
		String userId = (String) paramMap.get("userId");

		Map<String,Object> paraMap= new HashMap<String,Object>();

		ArrayList typeList = new ArrayList<String>();
		typeList.add(Constants.MABC_HEART);
		typeList.add(Constants.MABC_SLEEP);
		typeList.add(Constants.MABC_FIVE_HEART);

		paraMap.put("userId",userId);
		paraMap.put("typeList",typeList);

		List<Map<String, Object>> questionList = followEvaluationDAO.selectAppList(paraMap);

		if (questionList != null && questionList.size() > 0){

			for (int i = 0;i < questionList.size();i++){
				if (("mabc00009").equals(questionList.get(i).get("busiId")) || ("mabc00010").equals(questionList.get(i).get("busiId"))){
					questionList.get(i).put("ageState","0");
				} else if (("mabc500003").equals(questionList.get(i).get("busiId"))){
					questionList.get(i).put("ageState","1");
				}
				Date date = (Date) questionList.get(i).get("createTime");
				questionList.get(i).put("createTime",DateTimeUtil.formatDate(date,1));
			}
		}

		return questionList;
	}
}
